package com.heima.kafka.sample;

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

public class KafkaStreamDemo {

    public static void main(String[] args) {
        //kafka的配置信息
        Properties prop = new Properties();
        prop.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.128:9092");
        prop.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        prop.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        prop.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-quickstart");

        //创建Kafka流的构造者
        StreamsBuilder streamsBuilder = new StreamsBuilder();

        //自定流式处理的逻辑，将来主要写这个方法
        streamProcessor(streamsBuilder);

        //创建kafak的流式对象
        KafkaStreams kafkaStreams = new KafkaStreams(streamsBuilder.build(), prop);

        //执行流式处理
        kafkaStreams.start();

    }

    //真正执行流式处理的方法
    private static void streamProcessor(StreamsBuilder streamsBuilder) {
        //订阅指定的topic中的消息，进行处理,获取到KStream
        KStream<String, String> kStream = streamsBuilder.stream("heima-stream-topic1");

        //使用KStream执行流式计算的逻辑
        kStream.flatMapValues(new ValueMapper<String, Iterable<String>>() {

                    //对消息进行处理，返回value
                    @Override
                    public Iterable<String> apply(String value) {
                        //value:  "hello kafka" -> "hello","kafka"
                        return Arrays.asList(value.split(" "));
                    }
                })
                //进行分组，一个单词分成一组
                .groupBy((key, value) -> value)
                //指定事件时间的窗口，用多长时间进行分段
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                //计算单词出现的数量
                .count()
                //计算完成，再转为流
                .toStream()
                .map((key, value) -> {
                    System.out.println("key:" + key + "::" + "value:" + value);
                    return new KeyValue<>(key.key().toString(), value.toString());
                })
                .to("heima-stream-result1");

    }
}
